package cn.regexp.elasticjob.listener;

import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
import com.google.common.base.Charsets;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Date;

/**
 * 定时任务启动前后监听
 *
 */
@Component
public class MyElasticJobListener implements ElasticJobListener {
    @Value("${elastic.job.log.basePath}")
    private String basePath;
    @Value("${elastic.job.log.enable}")
    private Boolean enable;

    private static final Logger logger = LoggerFactory.getLogger(MyElasticJobListener.class);
    private long beginTime = 0;
    PrintStream old = System.out;
    ConsoleStream newStream=null;
    PrintStream printStream =null;
    // ByteArrayOutputStream byteArrayOutputStream = null;

    @Override
    public void beforeJobExecuted(ShardingContexts shardingContexts) {
        if (enable){
            newStream=new ConsoleStream(old);
            printStream = new PrintStream(newStream);
            System.setOut(printStream);
            System.setErr(printStream);
        }
        beginTime = System.currentTimeMillis();
        logger.info("{} start =======>",shardingContexts.getJobName());
        logger.info("start Time :{}",DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public void afterJobExecuted(ShardingContexts shardingContexts) {
        long endTime = System.currentTimeMillis();
        logger.info("{} executed <========",shardingContexts.getJobName());
        logger.info("endTime:{}",DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        logger.info("time-consuming:{}", (endTime - beginTime));
        if (enable){
            byte[] bytes = newStream.toByteArray();
            try {
               String fileDir = basePath + File.separator +shardingContexts.getJobName();
               File dir =new File(fileDir);
               if(!dir.exists()){
                   dir.mkdirs();
               }
               String filePath = fileDir+File.separator + DateFormatUtils.format(new Date(), "yyyy-MM-dd")+".log";
                if(!dir.exists()){
                    dir.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(filePath,true);
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.setOut(old);
        }
    }

}
